package com.ucl.web.controller.supplier;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.ucl.common.util.TreeBuilder;
import com.ucl.model.common.ApiResult;
import com.ucl.model.entity.supplier.Supplier;
import com.ucl.model.entity.supplier.SupplierTreeNode;
import com.ucl.service.supplier.SupplierService;
import com.ucl.web.controller.base.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api/supplier/info")
public class SupplierInfoController extends BaseController {

    @Autowired
    private SupplierService supplierService;

    @RequestMapping("getAllSupplier")
    public ApiResult getAllSupplier() {
        List<Supplier> list = supplierService.listTreeSupplier();
        List<SupplierTreeNode> supplierNodesList = Lists.newArrayList();
        if( list != null && !list.isEmpty() ){
            list.forEach( temp->{
                SupplierTreeNode supplierNodeNode = new SupplierTreeNode();
                BeanUtil.copyProperties( temp, supplierNodeNode);
                supplierNodesList.add( supplierNodeNode );
            } );
        }
        List<SupplierTreeNode> lastSupplierNodesList = TreeBuilder.buildSupplierTree( supplierNodesList );

        JSONObject json = new JSONObject();
        json.put( "supplierList", list);
        json.put( "supplierTree", lastSupplierNodesList);
        return ApiResult.ok("获取菜单树成功", json);
    }

    @RequestMapping("saveSupplier")
    public ApiResult saveSupplier(@RequestBody SupplierTreeNode supplier) {
        LOGGER.info(supplier.toString());
        supplierService.saveSupplier(supplier);
        return ApiResult.ok();
    }

    @RequestMapping("deleteSupplier")
    public ApiResult deleteSupplier(@RequestBody Supplier supplier) {
        LOGGER.info(supplier.toString());
        supplierService.deleteSupplier(supplier);
        return ApiResult.ok();
    }
}
